package com.jetpackframework.skin;

import android.app.Application;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.AssetManager;
import android.content.res.Resources;
import android.util.Log;

import com.jetpackframework.virtual.SkinResource;

import java.io.File;
import java.lang.reflect.Method;
import java.util.Observable;

public class SkinManager extends Observable {
    private static SkinManager manager;

    private SkinManager(){

    }
    public static synchronized SkinManager getInstance(){
        if (manager == null){
            manager = new SkinManager();
        }
        return manager;
    }
    /**
     * 加载资源包(皮肤包)
     * @param skinPath
     */
    public void loadSkin(Application application,String skinPath){
        File file = new File(skinPath);
        if (!file.exists()){
            return;
        }
        if (file.isDirectory()){
            return;
        }
        try {
            Resources resources = application.getResources();
            AssetManager manager = AssetManager.class.newInstance();
            Method addAssetPath = AssetManager.class.getMethod("addAssetPath", String.class);
            addAssetPath.invoke(manager,skinPath);
            Resources skinResource = new Resources(manager,resources.getDisplayMetrics(),resources.getConfiguration());
            PackageManager packageManager = application.getPackageManager();
            PackageInfo info = packageManager.getPackageArchiveInfo(skinPath, PackageManager.GET_UNINSTALLED_PACKAGES);
            Log.e("TAG",info+"");
            SkinResource.getInstance(application).applyResouce(info.packageName,skinResource);
        } catch (Exception e) {
            e.printStackTrace();
        }

        setChanged();
        notifyObservers(null);
    }
}